<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/4/16 0016
 * Time: 上午 10:21
 */

namespace app\single\command;


use app\single\model\RoleModel;
use app\single\model\TableMaxIdModel;
use app\single\model\VarModel;
use cmf\lib\Http;
use cmf\lib\Sign;
use think\Command;
use think\console\Input;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\facade\Cache;
use think\facade\Log;

class UpdatePlayer extends Command
{
    protected $serverInfo = [];

    /**
     * @param Input $input
     * @param Output $output
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    protected function execute($input, $output)
    {
        usleep(mt_rand(300, 10000));
        $limit = 500;
        $maxIdModel = new TableMaxIdModel();
        $maxId = $maxIdModel->getMaxId("role") ?: 0;
        $today = strtotime(date('Y-m-d'));
        //每天第一次上传 上传全部数据
        // $KEY = 'last_upload_date'.PLATFORM.PLAT_SERVER_ID ;

        // $res = Cache::get($KEY);
    //    print_r("res===>" . $res);
        // if (!$res || $res < $today) {

            // $maxId = 0;
            // Cache::set($KEY, $today);
        // }

        $roleModel = new RoleModel();
        $data = $roleModel
            ->alias("r")
//            ->leftJoin([config("database.game") . ".role_auto_fight" => "fpt"], "fpt.role_id = r.id")
            ->where("r.id", ">", $maxId)
//            ->where("reg_time", "<=", time() - 60)
            ->field("r.*")
            ->limit($limit)
            ->order("r.id ASC")
            ->select();
//        print_r("last_query_sql:" . $roleModel->getLastSql() . "\n");
        print_r("一共需要上传的玩家个数" . count($data) . "\n");
        //platform,plat_server,player_id,name,username,server_id,sex,level,power,reg_time,reg_date,login_ip,login_time,login_date,status

        if ($data) {
            $cache = Cache::store("file");
            $this->serverInfo = $cache->get("server_info");
            foreach ($data as $vo) {
                $maxId = $vo["id"];
                $params = [
                    "platform" => $vo["pf"],
                    "plat_server" => $vo["zone_id"],
                    "server_id" => $vo["zone_id"],
                    "username" => $vo["account"],
                    "player_id" => $vo["id"],
                    "name" => $vo["name"],
                    "sex" => $vo["sex"] ?? 0,
                    "level" => $vo["lev"] ?? 1,
                    "power" => $vo["fc"] ?? 1,
                    "login_time" => $vo["last_login_time"] ?? time(),
                    "reg_time" => $vo["reg_time"] ?? time(),
                    "login_ip" => $vo["last_login_ip"] ?? "127.0.0.1",
                    "login_date" => date('Y-m-d', $vo["last_login_time"]),
                    "status" => $vo["state"],
                    "time" => time(),
                ];
                $params["sign"] = Sign::buildMD5sign($params, config("secure." . GAME_NAME . '_key.CLIENT'));
//                var_dump($params);

                $API_URL = trim($this->serverInfo["api_url"]) . "/Client/update_player";
                $result = Http::post($API_URL, $params);
                echo ("update_player success,API:=>" . $API_URL . "params:=>" . json_encode($params) . "result=>" . json_encode($result, true)) . __LINE__ . PHP_EOL;

            }
            $maxIdModel->updateMaxId("role", $maxId);
        }
//        $this->checkSysConfig();
    }

    /**
     * 检查服务端配置
     * @return mixed
     */
    private function checkSysConfig()
    {

        $errMsg = [];
        $varModel = new VarModel();
        $port = $varModel->getValue("port");
        if ($port != $this->serverInfo["port"]) {
            $errMsg[] = "port不对应，应为" . $port;
        }
        $fileName = CMF_ROOT . "../server/config/sys.config";
        if (is_file($fileName)) {
            $content = getFileLines($fileName, 65, 75);
            //检测ip白名单是否有配置
            if (isset($content[7]) && !strpos($content[7], str_replace(".", ",", $this->serverInfo["ip"]))) {
                $errMsg[] = "white_ip error";
            }
        }
        $lastErrMsg = cache("last_error_msg");
        cache("last_error_msg", $errMsg);
        if ($lastErrMsg != $errMsg) {
            $params = [
                "platform" => PLATFORM,
                "plat_server" => PLAT_SERVER_ID,
                "content" => $errMsg ? implode("<br/>", $errMsg) : "",
                "time" => time()
            ];
            $params["sign"] = Sign::buildMD5sign($params, config("secure." . GAME_NAME . '_key.CLIENT'));
            $res = Http::post($this->serverInfo["api_url"] . "/client/report_sys_error", $params);
            return $res;
        }
    }
}